package com.longge.common.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;

import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;

/**
 * 获取网卡信息的工具类
 * @author roger yang
 *
 */
@Slf4j
public class NetworkUtils {
	private NetworkUtils() {}
	
	/**
	 *  获取所有的网卡
	 * @return
	 */
	public static List<NetworkInterface> getAllNetworkCards() {
		List<NetworkInterface> result = new ArrayList<>();
		try {
			Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
		
			while (enumeration.hasMoreElements()) {
				NetworkInterface net = enumeration.nextElement();
				result.add(net);
			}
		} catch (SocketException e) {
			log.error("获取网卡信息时异常", e);
			throw new RuntimeException(e);
		}
		return result;
	}
	
	/**
	 * 获取所有的可用（有IP地址）的网卡
	 * @return
	 */
	public static List<NetworkInterface> getAvailableNetworkCards() {
		List<NetworkInterface> cards = getAllNetworkCards();
		if(null!=cards && !cards.isEmpty()) {
			return cards.stream().filter(net -> {
				String ipv4 = getIpv4(net);
				if(null == ipv4) {
					return false;
				}
				return true;
			}).collect(Collectors.toList());
		}
		return Collections.emptyList();
	}
	
	/**
	 * 获取默认网卡的IP V4地址
	 * @return
	 */
	public static String getDefaultIpV4() {
		List<NetworkInterface> list = getAvailableNetworkCards();
		if(CollectionUtils.isEmpty(list)) {
			throw new RuntimeException("cann't find ipv4 network");
		}
		return getIpv4(list.get(0));
	} 
	
	/**
	 * 获取IP V4的地址
	 * @param net
	 * @return
	 * @throws SocketException
	 */
	public static String getIpv4(@NonNull NetworkInterface net) {
		String result = null;
		Enumeration<InetAddress> address = net.getInetAddresses();
		while(address.hasMoreElements()) {
			InetAddress addr = address.nextElement();
			String ip = addr.getHostAddress();
			if(ip.contains(":")) {
				if(log.isDebugEnabled()) {
					log.debug("this ip is ip v6 addrress : {}", ip);
				}
				continue;
			}
			result = ip;
		}
		return result;
	}
	
	/**
	 * 获取IP V6的地址
	 * @param net
	 * @return
	 * @throws SocketException
	 */
	public static String getIpv6(@NonNull NetworkInterface net) {
		String result = null;
		Enumeration<InetAddress> address = net.getInetAddresses();
		while(address.hasMoreElements()) {
			InetAddress addr = address.nextElement();
			String ip = addr.getHostAddress();
			if(!ip.contains(":")) {
				if(log.isDebugEnabled()) {
					log.debug("this ip is ip v4 addrress : {}", ip);
				}
				continue;
			}
			result = ip;
		}
		return result;
	}

	/**
	 * 获取mac地址
	 * @param net
	 * @return
	 * @throws SocketException
	 */
	public static String getMacAddress(@NonNull NetworkInterface net) {
		StringBuilder sb = new StringBuilder();
		
		byte[] bytes = null;
		try {
			bytes = net.getHardwareAddress();
		} catch (SocketException e) {
			log.error("获取mac信息异常", e);
			throw new RuntimeException(e);
		}
		if (bytes != null) {
			for (int i = 0; i < bytes.length; i++) {
				if (i != 0) {
					sb.append("-");
				}
				int tmp = bytes[i] & 0xff; // 字节转换为整数
				String str = Integer.toHexString(tmp);
				if (str.length() == 1) {
					sb.append("0").append(str);
				} else {
					sb.append(str);
				}
			}
			return sb.toString();
		}
		return null;
	}
}
